package com.bangmai.util;

import java.security.MessageDigest;
/**
 * MD5加密操作
 * 
 * @author dellpc
 *
 */

public class Md5Util {
	
	//获得MD5加密密码的方法
		public static String getMD5ofByte(byte[] data) {
				String origMD5 = null;
				try {
					MessageDigest md5 = MessageDigest.getInstance("MD5");
					byte[] result = md5.digest(data);
					origMD5 = byteArray2HexStr(result);
				} catch (Exception e) {
					e.printStackTrace();
				}
			return origMD5;
		}
		
		//处理字节数组得到MD5密码的方法
		private static String byteArray2HexStr(byte[] bs) {
				StringBuffer sb = new StringBuffer();
				for (byte b : bs) {
					sb.append(byte2HexStr(b));
				}
				return sb.toString();
		}

		//字节标准移位转十六进制方法
		private static String byte2HexStr(byte b) {
				String hexStr = null;
				int n = b;
				if (n < 0) {
					n = b & 0x7F + 128;
				}
				hexStr = Integer.toHexString(n / 16) + Integer.toHexString(n % 16);
				return hexStr.toUpperCase();
		}
		//MD5加密验证
		public static boolean verifySignMsg(String rsaKey, String msg){
			String digest = msg.replaceAll("^([\\s\\S]*)(<VnbMessage>[\\s\\S]*<Sign>)([\\s\\S]*)(</Sign>[\\s\\S]*)", "$3");
			String msgBeforeSigned = msg.replaceAll("^([\\s\\S]*)(<VnbMessage>[\\s\\S]*<Sign>)([\\s\\S]*)(</Sign>[\\s\\S]*)", "$2$4");
			try {
				String digestComputed = getMD5ofByte((msgBeforeSigned + rsaKey).getBytes("UTF-8"));
				if(!digestComputed.equals(digest))
					return false;
				return true;
			} catch (Exception e) {
				return false;
			}
		} 
}
